<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <!-- Eeasy UI Styles-->
    <link href="easyui/default/easyui.css" rel="stylesheet"/>
    <!-- Eeasy UI Icon -->
    <link href="easyui/icon.css"/>
    <!-- jQuery Js -->
    <script src="js/jquery-1.10.2.js"></script>
    <!-- Eeasy UI Js -->
    <script src="easyui/jquery.easyui.min.js"></script>
    <script src="easyui/locale/easyui-lang-zh_CN.js"></script>
    <script src="js/jquery.ocupload-1.1.2.js"></script>
    <style rel="stylesheet">
        .datagrid-cell-c1-picture>div{
            left: 43%;
        }
    </style>
</head>
<body>
<div id="tb-toolbar">
    <a href="#" class="easyui-linkbutton" onclick="addrow()" data-options="plain:true">新增</a>
    <a href="#" class="easyui-linkbutton" onclick="deleterow()" data-options="plain:true">删除</a>
</div>
<table  id="admintable">

</table>
<script type="text/javascript">
    //记录当前行数据
    var rowData=null;
    //初始化一键上传
    var initUpload=false;
    $(function() {
        $('#admintable').datagrid({
            toolbar: '#tb-toolbar',//数据网格（datagrid）面板的头部工具栏
            striped:true,//奇偶行使用不同背景色
            nowrap:true,//把数据显示在一行里
            method:'post',//请求远程数据的方法（method）类型
            width: 1030,
            fitColumns:true,//自动扩大或缩小列的尺寸以适应网格的宽度并且防止水平滚动
            idField: 'id',//指示哪个字段是标识字段
            pagination:true,//分页
            pageNumber:1,//初始化页码
            pageSize:10,//初始化页面尺寸
            pageList:[10],//页面尺寸数组
            checkOnSelect:true,//checkOnSelect
            url: '/back/queryAllActivityByPage',
            queryParams:{},//当请求远程数据时，发送的额外参数
            columns: [
                [{
                    field:'checkbox',
                    checkbox:true,
                    align:'center'
                },
                    {
                        field: 'id',
                        title: 'ID',
                        align: 'center',
                        width: 60
                    },
                    {
                        field: 'theme',
                        title: '主题',
                        align: 'center',
                        width: 100,
                        editor: 'text'
                    },
                    {
                        field: 'description',
                        title: '描述',
                        width: 120,
                        align: 'center',
                        editor: 'text'
                    },
                    {
                        field: 'address',
                        title: '地址',
                        width: 120,
                        align: 'center',
                        editor: 'text'
                    },
                    {
                        field: 'picture',
                        title: '图片',
                        width: 150,
                        align: 'center',
                        formatter: function (value,row,index) {
                            var btn;
                            if(row.editing){
                                btn='<a href="javascript:void(0)"   class="upload-pic" onmouseover="showPic(this,\''+value+'\')" onmouseout="hidePic(this)" >选择</a>';
                            }else {
                                btn='<a href="javascript:void(0)" onmouseover="showPic(this,\''+value+'\')" onmouseout="hidePic(this)">查看</a>';
                            }
                            return btn;
                        },
                    },
                    {
                        field: 'actDate',
                        title: '活动日期',
                        width: 120,
                        align: 'center',
                        editor: 'datebox'
                    },
                    /* {
                     field: 'status',
                     title: 'Status',
                     width: 50,
                     align: 'center',
                     editor: {
                     type: 'checkbox',
                     options: {
                     on: 'P',
                     off: ''
                     }
                     }
                     },*/
                    {
                        field: 'action',
                        title: '操作',
                        width: 100,
                        align: 'center',
                        formatter: function(value, row, index) {
                            if (row.editing) {
                                var s = '<a href="#" onclick="saverow(this)">保存</a> ';
                                var c = '<a href="#" onclick="cancelrow(this)">取消</a>';
                                return s + c;
                            } else {
                                var e = '<a href="#" onclick="editrow(this)">编辑</a> ';
                                var d = '<a href="#" onclick="deleterow(this)">删除</a>';
                                return e + d;
                            }
                        }
                    }]],
            onBeforeEdit: function(index, row) {
                row.editing = true;
                rowData=row;
                updateActions(index);
            },
            onAfterEdit: function(index, row) {
                row.editing = false;
                rowData.editing=false;
                updateActions(index);
            },
            onCancelEdit: function(index, row) {
                row.editing = false;
                rowData.editing=false;
                updateActions(index);
            },
            onClickRow: function (rowIndex,row) {
                rowData=row;
            },
        });
    });
    function updateActions(index) {
        $('#admintable').datagrid('refreshRow',index);
        $('#admintable').datagrid('updateRow', {
            index: index,
            row: rowData
        });
    }
    function getRowIndex(target) {
        var tr = $(target).closest('tr.datagrid-row');
        return parseInt(tr.attr('datagrid-row-index'));
    }
    function addrow(){
        rowData={editing:true};
        $('#admintable').datagrid('insertRow',{
            index: 0,
            row: rowData
        })
        $('#admintable').datagrid('beginEdit',0);
    }
    function editrow(target) {
        $('#admintable').datagrid('beginEdit', getRowIndex(target));
    }
    function deleterow(target) {
        //获取选择的行
        var rows=$('#admintable').datagrid('getSelections');
        if(rows.length<1){
            $.messager.alert('系统提示','至少选择一行','warning');
            return ;
        }
        $.messager.confirm('系统提示', '确定删除吗?',
            function(r) {
                if (r) {
                    var ids=new Array();
                    //遍历选择的行
                    for(var i=0;i<rows.length;i++){
                        ids.push(row[i].id);
                    }
                    //后台删除
                    var flag=sendAjax({
                        url: '/back/deleteActivity',
                        data:{'ids':ids},
                        successText: '删除成功',
                        errorText: '删除失败'
                    })
                    if(flag){
                        $('#admintable').datagrid('deleteRow', getRowIndex(target));
                    }else{
                        rowData.editing=false;
                        updateActions(getRowIndex(target));
                    }
                }
            });
    }
    function saverow(target) {
        var url='/back/addActivity';
        var rowIndex=getRowIndex(target);
        $('#admintable').datagrid('endEdit', rowIndex);
        var data=getRow(rowIndex);
        var newRow=data;
        rowData=data;
        if(rowData.id){
            //更新
            url= '/back/updateActivity';
        }else {
            //添加
            url: '/back/addActivity';
        }
        $.ajax({
            url: url,
            type: 'post',
            data: data
        }).done(function(json){
            if(json){
                newRow=json;
                $.messager.alert('系统消息','保存成功','info');
            }else{
                rowData.editing=true;
                updateActions(rowIndex);
                $.messager.alert('系统消息','保存失败','error');
            }
            $('#admintable').datagrid('updateRow',{
                index: rowIndex,
                row: newRow
            })
        }).fail(function(){
            rowData.editing=true;
            updateActions(rowIndex);
            $.messager.alert('系统消息','服务器正忙，请稍后再试...','error');
        })
    }

    function cancelrow(target) {
        $('#admintable').datagrid('cancelEdit', getRowIndex(target));
    }
    //获取指定索引的行
    function getRow(index){
        var rows=$('#admintable').datagrid('getRows');
        for(var i=0;i<rows.length;i++){
            var row=rows[i];
            var rowIndex=$('#admintable').datagrid('getRowIndex',row);
            if(rowIndex==index){
                return row;
            }
        }
    }
    //显示图片
    function showPic(target,value){
        if(!initUpload){
            uploadPic();
            initUpload=true;
        }
        if($(target).children('img')){
            var img='<img src="/upload/'+value+'" style="width:50px;height:50px;position: absolute;z-index: 999;"/>';
            $(target).append(img);
        }else {
            $(target).children('img').show();
        }
    }
    //隐藏图片
    function hidePic(target){
        $(target).children('img').hide();
    }

    function uploadPic(){
        var i=$('a.upload-pic');
        $('a.upload-pic').upload({
            action: '/back/activityUpload',
            name:'file',
            // params:{'carId':accidentCarId,'time':accidentTime},
            onComplete:function(data){
                if(data&&data!="error"){
                    rowData.picture=data;
                    alert('success');
                }else{
                    alert('error');
                }
            }
        })
    }
    //发送ajax请求
    function sendAjax(obj) {
        $.ajax({
            url: obj.url,
            type: 'post',
            data:obj.data
        }).done(function (msg) {
            if(msg=="error"){
                $.messager.alert('系统消息',obj.errorText,'error');
                return false;
            }else if(msg=="ok"){
                $.messager.alert('系统消息',obj.successText,'error');
                return true;
            }
        }).fail(function () {
            $.messager.alert('系统消息','服务器正忙，请稍后再试...','error');
            return false;
        })
    }
    $.extend($.fn.datagrid.defaults.editors, {
        text: {
            init: function(container, options){
                var input = $('<input  type="text" style="text-align: center" class="datagrid-editable-input">').appendTo(container);
                return input;
            },
            destroy: function(target){
                $(target).remove();
            },
            getValue: function(target){
                return $(target).val();
            },
            setValue: function(target, value){
                $(target).val(value);
            },
            resize: function(target, width){
                $(target)._outerWidth(width);
            }
        }
    });
</script>
</body>
</html>